/**
 * Author:  Radoslaw Karpowicz
 * Contact: radek.karpowicz@gmail.com
 * Version: 0.1.0
 * Licensed under LGPL v3
 *
 * Based on informations located at:
 * http://wiibrew.org/wiki/Wiimote/Extension_Controllers
 * http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1259091426
 **/
#if !defined(DUOFX_H)
#define DUOFX_H

#ifndef CPU_FREQ
#define CPU_FREQ 16000000L
#endif

#define DEBUG_MODE      true
#define CONTROLLER_ADDR 0x52
#define DATA_BYTES_LEN  0x06
#define NULL_BYTES_LEN  0x01
#define LED_PIN         13

#define BOUND_RATE      115200
#define INIT_TIMEOUT    1000 // send init request with 1s. delay
#define MAX_INIT_PROBES 10
#define CALIBRATION_DELAY 3000 // wait 3s. before calibration

#define JOY_X_AXIS_ADDR   0
#define JOY_Y_AXIS_ADDR   1
#define ACCEL_X_AXIS_ADDR 2
#define ACCEL_Y_AXIS_ADDR 3
#define ACCEL_Z_AXIS_ADDR 4
#define Z_C_BUTTON_ADDR   5


class DuoFxController {

public:
  DuoFxController();
  ~DuoFxController();
  void PrintIdent();
  void SetDebugMode(bool debugMode);
  void SendNullBytes(unsigned int byteCount);
  void SerialPrintCoordinates(char* valueSeparator, char* lineSeparator);
  void TurnOnSyncDiode();
  void TurnOffSyncDiode();
  bool Init();
  bool IsValidDuoFXController();
  void ReceiveCoordinates(int accelRatio);
  bool IsInitialized();
  void CalibrateController();
  int GetJoystickAngle();
  bool debug_mode;

  // Duo FX Sensors
  typedef struct {
    uint8_t  joy_x_axis, joy_y_axis;
    uint16_t accel_x_axis, accel_y_axis, accel_z_axis;
    bool     z_button, c_button;
  } DuoFXAxis;

  // Calibration
  typedef struct {
    uint8_t max_joy_x_axis : 246, min_joy_x_axis,
            max_joy_y_axis : 246, min_joy_y_axis,
            init_joy_x_axis: 120, init_joy_y_axis: 126;

    uint16_t max_accel_x_axis, min_accel_x_axis,
             max_accel_y_axis, min_accel_y_axis,
             max_accel_z_axis, min_accel_z_axis;
  } Calibration;

private:
  bool duofx_initialized;
  bool IsEndOfTransmission();
};

#endif

